package com.xzzz.irda.auth.core.util;

import cn.hutool.core.util.StrUtil;
import com.xzzz.irda.auth.core.authorization.Authorization;
import com.xzzz.irda.auth.core.constants.AuthConstant;
import com.xzzz.irda.auth.core.exception.AuthException;
import com.xzzz.irda.auth.core.exception.AuthRCode;


/**
 * @author wangyf
 * 
 */
public class TokenUtil {

    /**
     * 截取 token 前缀(Bearer), 返回 token
     *
     * @param tokenStr token 字符串
     * @return token
     */
    public static String cutPrefix(String tokenStr) {
        if (tokenStr == null || tokenStr.length() == 0) {
            return null;
        }
        if (StrUtil.startWith(tokenStr, AuthConstant.HEADER_TOKEN_PREFIX)) {
            return StrUtil.replace(tokenStr, AuthConstant.HEADER_TOKEN_PREFIX, "");
        }
        return tokenStr;
    }

    /**
     * 获取授权 key
     * @param authorization
     * @return
     */
    public static String buildTokenKey(Authorization authorization) {
        return AuthConstant.Redis.KEY_AUTHORIZATION + authorization.getAccessToken().getToken();
    }

    public static String buildTokenKey(String token) {
        return AuthConstant.Redis.KEY_AUTHORIZATION + token;
    }


    /**
     * 获取唯一有效授权的key
     *
     * @param authorization 授权对象
     * @return 唯一有效token的key
     */
    public static String buildUniqueTokenKey(Authorization authorization) {
        if (authorization == null || authorization.getAccessToken() == null) {
            throw new AuthException(AuthRCode.INVALID_TOKEN);
        }
        return AuthConstant.Redis.UNIQUE_TOKEN_PREFIX +
                authorization.getAccessToken().getUserId() +
                AuthConstant.Redis.UNIQUE_TOKEN_INFIX +
                authorization.getClientId();
    }
}
